﻿using Microsoft.AspNetCore.Mvc;
using XKPlatform.DataModels;
using XKPlatform.Common;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using XKPlatform.Common.Const;
using Microsoft.AspNetCore.Http;

namespace XKPlatform.Controllers
{
    public class ToolController : BaseController
    {

        //private MongoDBHelper<BsonDocument> mongo = null;
        public ToolController(IHttpContextAccessor httpContext) : base(httpContext)
        {

        }

        //List<TableViewModel> mdlist = new List<TableViewModel>();


        #region 表格管理

        #region 表格查询
        public JsonResult getTableList(Search search)
        {

            var fields = QuerySuite.GetTableFieldsSql<SysTable>(new string[] { "Remarks", "RecordStatus", "ModifiedBy", "ModifiedOn", "tempTable", "tableOptions", "tableCols" });
            QuerySuite querySuite = new QuerySuite("SysTable where RecordStatus=0", fields, search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #region 保存表格
        [HttpPost]
        public JsonResult saveTable(SysTable model)
        {


            QuerySuite querySuite = new QuerySuite("SysTable where TableNo=@TableNo and TableID!=@TableID  ");
            querySuite.AddParam("TableID", model.TableID);
            querySuite.AddParam("TableNo", model.TableNo);
            querySuite.AddParam("RecordStatus", "=", 0);

            if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
                return Json(new { code = 1, msg = "表格编号已存在。" });

            if (model.TableID == new Guid())
            {
                model.TableID = Guid.NewGuid();
                model.CreatedOn = DateTime.Now;
                model.CreatedBy = userInfo.UserNo;
                model.RecordStatus = false;
                SqlHelper.InsertSql(model);

            }
            else
            {
                model.ModifiedBy = userInfo.UserNo;
                model.ModifiedOn = DateTime.Now;
                SqlHelper.UpdateSql(model, "TableID", new string[] { "CreatedOn", "CreatedBy", "RecordStatus" });
            }

            var path = HttpContextCore.Env.WebRootPath;

            string json_Path = path + "/json/table/" + model.TableNo.ToString() + ".json";
            System.IO.File.WriteAllText(json_Path, model.tempTable);

            //FileStream fs = new FileStream(json_Path, FileMode.OpenOrCreate, FileAccess.Write);
            //StreamWriter sw = new StreamWriter(fs);
            //fs.SetLength(0);
            //sw.WriteLine(model.tempTable);
            //sw.Close();
            //fs.Close();

            //OperateLog.InsertList<OrderModel>(pList, "OrderModel");
            //TableViewModel temp = new TableViewModel(model.tempTable);
            //OperateLog.Insert<TableViewModel>(temp, model.TableID.ToString());

            //    var document = new BsonDocument
            //{
            //    { "tempTable", model.tempTable }

            //};
            //    mongo.InsertOneData(document);//插入一行数据
            return Json(new { code = 0, result = model.TableID, updateData = model });


        }
        #endregion

        #region 保存表格json
        [HttpGet]
        public JsonResult buildTable()
        {

            QuerySuite querySuite = new QuerySuite("SysTable where RecordStatus=0");

            List<SysTable> list = ModelHelper<SysTable>.ConvertToModelList(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

            var path = HttpContextCore.Env.WebRootPath;

            foreach (var model in list)
            {
                string json_Path = path + "/json/table/" + model.TableNo.ToString() + ".json";

                System.IO.File.WriteAllText(json_Path, model.tempTable);

                //using (FileStream fs = System.IO.File.Create(json_Path))
                //{
                //    StreamWriter sw = new StreamWriter(fs);
                //    fs.SetLength(0);
                //    sw.WriteLine(model.tempTable);
                //    sw.Close();
                //    fs.Flush();
                //}

                //FileStream fs = new FileStream(json_Path, FileMode.OpenOrCreate, FileAccess.Write);
                //StreamWriter sw = new StreamWriter(fs);
                //fs.SetLength(0);
                //sw.WriteLine(model.tempTable);
                //sw.Close();
                //fs.Close();
            }

            return Json(new { code = 0 });


        }
        #endregion

        #region 删除表格
        [HttpPost]
        public JsonResult delTable(string ids)
        {

            QuerySuite querySuite = new QuerySuite("SysTable");
            querySuite.AddParam("TableID", "inid", ids);
            querySuite.AddParam("ModifiedBy", userInfo.UserNo);
            SqlHelper.ExecuteSql("update SysTable set RecordStatus=1,ModifiedOn=getdate(),ModifiedBy=@ModifiedBy from " + querySuite.FromSql, querySuite.Params);

            return Json(new { code = 0 });


        }
        #endregion

        #region 获取表格信息

        public JsonResult getTableInfo(Guid? dataId)
        {

            QuerySuite querySuite = new QuerySuite("SysTable");
            querySuite.AddParam("TableID", "=", dataId);

            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);

            return Json(new { code = 0, data = ModelHelper<SysTable>.ConvertToModel(ds.Tables[0]) });

        }
        public JsonResult getTableConfig(string tableNo)
        {
            QuerySuite querySuite = new QuerySuite("SysTable where RecordStatus=0", "tempTable");
            querySuite.AddParam("TableNo", "=", tableNo);

            var tempTable = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);

            querySuite = new QuerySuite("SysForm where RecordStatus=0", "tempForm");
            querySuite.AddParam("FormNo", "=", tableNo + "-search-form");

            var searchForm = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);

            querySuite = new QuerySuite("SysForm where RecordStatus=0", "tempForm");
            querySuite.AddParam("FormNo", "=", tableNo + "-form");

            var subForm = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);

            return Json(new { code = 0, data = new { tempTable, searchForm, subForm } });

        }
        #endregion

        #endregion

        #region 表单管理

        #region 获取表单列表
        public JsonResult getFormList(Search search)
        {
            var fields = QuerySuite.GetTableFieldsSql<SysForm>(new string[] { "Remarks", "RecordStatus", "ModifiedBy", "ModifiedOn", "tempForm", "FormFields" });

            QuerySuite querySuite = new QuerySuite(@"SysForm where RecordStatus=0", fields, search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);
            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        #endregion

        #region 获取表单下拉列表
        public JsonResult getFormSelect(Search search)
        {
            QuerySuite querySuite = new QuerySuite("SysForm where RecordStatus=0", "FormID,FormName,FormNo", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        #endregion

        #region 保存表单
        public JsonResult saveForm(SysForm model, bool CreateTable, bool Identity)
        {
            QuerySuite querySuite = new QuerySuite("SysForm where  FormID!=@FormID and FormNo=@FormNo");
            querySuite.AddParam("FormID", model.FormID);
            querySuite.AddParam("FormNo", model.FormNo);
            if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
                return Json(new { code = 1, msg = "模板编号已存在。" });
            if (model.FormID == new Guid())
            {
                model.FormID = Guid.NewGuid();
                model.CreatedOn = DateTime.Now;
                model.CreatedBy = userInfo.UserNo;
                model.RecordStatus = false;

                SqlHelper.InsertSql(model);
            }
            else
            {
                model.ModifiedBy = userInfo.UserNo;
                model.ModifiedOn = DateTime.Now;
                SqlHelper.UpdateSql(model, "FormID", new string[] { "CreatedOn", "CreatedBy", "RecordStatus" });
            }

            if (CreateTable == true)
            {
                var sql = "";

                string[] defaultFileds = new string[] { "ID", "No", "_FormID", "CreatedOn", "CreatedBy", "ModifiedBy", "ModifiedOn", "ImportBatch", "RecordStatus" };
                List<FormFiled> fileds = JsonHelper.ToList<FormFiled>(model.FormFields);
                var remarks = "";
                foreach (var item in fileds)
                {
                    //默认字段
                    if (((IList)defaultFileds).Contains(item.itemName) || item.elementType == "textEdit")
                        continue;
                    switch (item.dataType)
                    {
                        case "int":
                            sql += ",[" + item.itemName + "] int NULL";
                            break;
                        case "decimal":
                            sql += ",[" + item.itemName + "] decimal(8,3) NULL";
                            break;
                        case "dateTime":
                        case "sysTime":
                            sql += ",[" + item.itemName + "] datetime NULL";
                            break;
                        case "bit":
                            sql += ",[" + item.itemName + "] bit NULL";
                            break;
                        case "uuid":
                            sql += ",[" + item.itemName + "] uniqueidentifier NULL";
                            break;
                        default:
                            sql += ",[" + item.itemName + "] nvarchar(" + (!string.IsNullOrEmpty(item.maxLen) ? item.maxLen : "50") + ") COLLATE Chinese_PRC_CI_AS NULL";
                            break;
                    }

                    remarks += @"EXEC sp_addextendedproperty 'MS_Description', N'" + item.fieldName + "', 'SCHEMA', N'dbo', 'TABLE', N'" + model.FormNo + "', 'COLUMN', N'" + item.itemName + "'";

                }
                string createSql = @"
IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[" + model.FormNo + @"]') AND type IN ('U'))
DROP TABLE [dbo].[" + model.FormNo + @"]

CREATE TABLE [dbo].[" + model.FormNo + @"] (
[ID] int  IDENTITY(1,1) NOT NULL,
[No] uniqueidentifier  NOT NULL,
[_FormID] uniqueidentifier  NOT NULL" + sql + @"

,[CreatedBy] nvarchar(50) COLLATE Chinese_PRC_CI_AS  NULL,
[CreatedOn] datetime  NULL,
[ModifiedBy] nvarchar(50) COLLATE Chinese_PRC_CI_AS  NULL,
[ModifiedOn] datetime  NULL,
[RecordStatus] bit  NULL,
[ImportBatch] int  NULL
)"
+ remarks
+ @"ALTER TABLE [dbo].[" + model.FormNo + @"] ADD CONSTRAINT [PK_" + model.FormNo + @"] PRIMARY KEY CLUSTERED ([ID])";

                SqlHelper.ExecuteSql(createSql);
            }

            var path = HttpContextCore.Env.WebRootPath;
            string json_Path = path + "/json/form/" + model.FormNo.ToString() + ".json";

            System.IO.File.WriteAllText(json_Path, model.tempForm);

            //FileStream fs = new FileStream(json_Path, FileMode.OpenOrCreate, FileAccess.Write);
            //StreamWriter sw = new StreamWriter(fs);
            //fs.SetLength(0);
            //sw.WriteLine(model.tempForm);
            //sw.Close();
            //fs.Close();

            return Json(new { code = 0, result = model.FormID, updateData = model });

        }
        #endregion

        #region 保存表单json
        [HttpGet]
        public JsonResult buildForm()
        {
            QuerySuite querySuite = new QuerySuite("SysForm where RecordStatus=0");

            List<SysForm> list = ModelHelper<SysForm>.ConvertToModelList(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

            var path = HttpContextCore.Env.WebRootPath;

            foreach (var model in list)
            {
                string json_Path = path + "/json/form/" + model.FormNo.ToString() + ".json";

                System.IO.File.WriteAllText(json_Path, model.tempForm);

                //LogHelper.SaveLog("buildForm", json_Path);
                //using (FileStream fs = System.IO.File.Create(json_Path))
                //{
                //    StreamWriter sw = new StreamWriter(fs);
                //    fs.SetLength(0);
                //    sw.WriteLine(model.tempForm);
                //    sw.Close();
                //    fs.Flush();
                //}

                //FileStream fs = new FileStream(json_Path, FileMode.OpenOrCreate, FileAccess.Write);
                //StreamWriter sw = new StreamWriter(fs);
                //fs.SetLength(0);
                //sw.WriteLine(model.tempForm);
                //sw.Close();
                //fs.Close();
            }

            return Json(new { code = 0 });


        }
        #endregion

        #region 获取表单
        public JsonResult getFormInfo(Guid? dataId)
        {
            QuerySuite querySuite = new QuerySuite("SysForm");
            querySuite.AddParam("FormID", "=", dataId);
            SysForm model = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
            return Json(new { code = 0, data = model });

        }
        public JsonResult getFormFields(Guid? dataId)
        {
            QuerySuite querySuite = new QuerySuite("SysForm");
            querySuite.AddParam("FormID", "=", dataId);
            SysForm model = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
            return Json(new { code = 0, data = new { model.FormFields, model.FormNo } });

        }
        public JsonResult getFormConfig(string formNo)
        {

            QuerySuite querySuite = new QuerySuite("SysForm where RecordStatus=0", "tempForm");
            querySuite.AddParam("FormNo", "=", formNo);

            var tempForm = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);

            return Json(new { code = 0, data = new { tempForm } });

        }
        #endregion

        #region 删除表单模板
        public JsonResult delForm(string ids)
        {
            QuerySuite querySuite = new QuerySuite("SysForm");
            querySuite.AddParam("FormID", "inid", ids);
            querySuite.AddParam("ModifiedBy", userInfo.UserNo);
            SqlHelper.ExecuteSql("update SysForm set RecordStatus=1,ModifiedOn=getdate(),ModifiedBy=@ModifiedBy from " + querySuite.FromSql, querySuite.Params);

            return Json(new { code = 0 });

        }
        #endregion

        #endregion

        #region 动态表格

        public JsonResult getFormDataList(Search search, Guid? FormID)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            LogHelper.SaveLog("getFormDataList===FormID:", querySuite.SelectSql + "====" + FormID);
            if (table == null || string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString(); 
           
            querySuite = new QuerySuite(tableName + " a left join SysUser b on a.CreatedBy=b.UserNo where a.RecordStatus=0", "a.*,b.UserName CreatedByUserName", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
       
        public JsonResult getFormDataList_ThirdParty(Search search, Guid? FormID)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null || string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();

            querySuite = new QuerySuite(tableName, "*", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, GlobleConst.OrginalDataContext, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        public JsonResult getFormDataListRetail_ThirdParty(string tid, Guid? FormID)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null && string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();
            string formSql = tableName + " where 1=1";
            querySuite = new QuerySuite(formSql, "*");
            if (!string.IsNullOrEmpty(tid))
            {
                querySuite.AddParam("tid", "=", tid);
            }
            else
            {
                querySuite.AddFilter("and 0 = 1");
            }
            DataSet ds = SqlHelper.Query(querySuite.LimitSql, GlobleConst.OrginalDataContext, querySuite.Params);
            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });


        }
        public JsonResult getFormDataList_New(Search search, Guid? FormID)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null && string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();

            querySuite = new QuerySuite(tableName + " a left join SysUser b on a.ModifiedBy=b.UserNo where a.RecordStatus=0", "a.*,b.UserName CreatedByUserName", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        public JsonResult saveFormData(Guid? _FormID)
        {
            if (!_FormID.HasValue)
                return Json(new { code = 1, msg = "表单不存在" });

            QuerySuite querySuite = new QuerySuite("SysForm");
            querySuite.AddParam("FormID", "=", _FormID);
            SysForm model = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

            if (model == null)
                return Json(new { code = 1, msg = "表单不存在" });

            List<FormFiled> formFiledList = JsonHelper.ToList<FormFiled>(model.FormFields);
            //List<string> filedKeys = new List<string>();

            List<string> keys = new List<string>();
            List<string> values = new List<string>();
            List<string> upValues = new List<string>();
            List<SqlParameter> _params = new List<SqlParameter>();

            var formKeys = Request.Form.Keys;

            var isAdd = false; Guid RNo = Guid.Empty; int RID = 0;

            string[] defaultFileds = new string[] { "ID", "No", "RNo", "_FormID", "_RFormID", "CreatedOn", "CreatedBy", "ModifiedBy", "ModifiedOn", "ImportBatch", "RecordStatus" };
            var notUpdateFileds = (IList)defaultFileds;

            foreach (var item in formFiledList)
            {
                if (item.elementType == "textEdit")
                    continue;

                //filedKeys.Add(item.itemName);
                if (formKeys.Contains(item.itemName) && !string.IsNullOrEmpty(Request.Form[item.itemName].ToString()))
                {
                    keys.Add(item.itemName);

                    //插入的参数值
                    values.Add("@" + item.itemName);

                    //修改的参数值 CreatedOn CreatedBy RecordStatus 在表单不出现，ID No _FormID 不修改
                    if (item.itemName != "ID" && item.itemName != "No" && item.itemName != "_FormID")
                        upValues.Add(item.itemName + "=@" + item.itemName);

                    _params.Add(new SqlParameter("@" + item.itemName, Request.Form[item.itemName].ToString()));
                }
                if (!formKeys.Contains(item.itemName) && !notUpdateFileds.Contains(item.itemName) && item.elementType != "hidden")
                    upValues.Add(item.itemName + "=null");
                //新增数据
                if (item.itemName == "ID" && string.IsNullOrEmpty(Request.Form[item.itemName].ToString()))
                {

                    isAdd = true;

                    keys.Add("No");
                    values.Add("@No");
                    RNo = Guid.NewGuid();
                    _params.Add(new SqlParameter("@No", RNo));

                    keys.Add("CreatedOn");
                    values.Add("@CreatedOn");
                    _params.Add(new SqlParameter("@CreatedOn", DateTime.Now));

                    keys.Add("CreatedBy");
                    values.Add("@CreatedBy");
                    _params.Add(new SqlParameter("@CreatedBy", userInfo.UserNo));

                    keys.Add("RecordStatus");
                    values.Add("@RecordStatus");
                    _params.Add(new SqlParameter("@RecordStatus", false));
                }
                else if (item.itemName == "ID" && !string.IsNullOrEmpty(Request.Form[item.itemName].ToString()))
                {
                    upValues.Add("ModifiedBy=@ModifiedBy");
                    _params.Add(new SqlParameter("@ModifiedBy", userInfo.UserNo));
                    upValues.Add("ModifiedOn=@ModifiedOn");
                    _params.Add(new SqlParameter("@ModifiedOn", DateTime.Now));
                }

                if (isAdd && item.itemName == "Org")
                {
                    keys.Add("Org");
                    values.Add("@Org");
                    _params.Add(new SqlParameter("@Org", userInfo.Org));
                }
            }

            if (isAdd)
            {
                StringBuilder sql = new StringBuilder();
                sql.Append("Insert into " + model.FormNo);
                sql.Append("(" + string.Join(",", keys) + ")");
                sql.Append(" values(" + string.Join(",", values) + ")");
                RID = SqlHelper.ExecuteInsertSql(sql.ToString(), _params.ToArray());
            }
            else
            {
                StringBuilder sql = new StringBuilder();
                sql.Append("update " + model.FormNo);
                sql.Append(" set " + string.Join(",", upValues));
                sql.Append(" where ID = @ID");
                SqlHelper.ExecuteSql(sql.ToString(), _params.ToArray());
            }

            if (model.NextFormID.HasValue && isAdd)
            {
                querySuite = new QuerySuite("SysForm");
                querySuite.AddParam("FormID", "=", model.NextFormID);
                SysForm nextModel = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
                return Json(new { code = 0, data = new { nextModel.FormID, nextModel.FormNo, RID, RNo, nextModel.tempForm } });
            }

            return Json(new { code = 0 });

        }

        public JsonResult delFormData(string ids, Guid? FormID)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null && string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();

            querySuite = new QuerySuite(tableName);
            querySuite.AddParam("No", "inid", ids);
            querySuite.AddParam("ModifiedBy", userInfo.UserNo);
            SqlHelper.ExecuteSql("update " + tableName + " set RecordStatus=1,ModifiedOn=getdate(),ModifiedBy=@ModifiedBy from " + querySuite.FromSql, querySuite.Params);

            return Json(new { code = 0 });

        }
        public JsonResult delFormData_NEW(string ids, Guid? FormID, string delname)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null && string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();

            querySuite = new QuerySuite(tableName);
            querySuite.AddParam(delname, "inid", ids);
            querySuite.AddParam("ModifiedBy", userInfo.UserNo);
            SqlHelper.ExecuteSql("update " + tableName + " set RecordStatus=1,ModifiedOn=getdate(),ModifiedBy=@ModifiedBy from " + querySuite.FromSql, querySuite.Params);

            return Json(new { code = 0 });

        }

        public JsonResult delFormData_LS(string ids, Guid? FormID, string delname)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null && string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();
            SqlHelper.ExecuteSql(string.Format("delete {0} where {1} ='{2}'", tableName, delname, ids));

            return Json(new { code = 0 });

        }

        public JsonResult getFormData(Guid? _FormID, Guid? No)
        {
            if (!_FormID.HasValue)
                return Json(new { code = 1, msg = "表单不存在" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo,FormFields");
            querySuite.AddParam("FormID", "=", _FormID);
            SysForm model = ModelHelper<SysForm>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);

            if (model == null)
                return Json(new { code = 1, msg = "表单不存在" });

            querySuite = new QuerySuite(model.FormNo);
            querySuite.AddParam("RecordStatus", "=", "0");

            querySuite.AddParam("No", "=", No);

            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]) });

        }
        #endregion

        public class FormFiled
        {
            public string dataType { get; set; }
            public string maxLen { get; set; }
            public string elementType { get; set; }
            public string itemName { get; set; }
            public string fieldName { get; set; }

        }
    }
}
